<template>
  <ContentDetailWrap :title="t('inventory.detail')" @back="push('/market/industryNews')">
    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
    </template>
    <!--    回显-->
    <Descriptions :schema="allSchemas.detailSchema" :data="currentRow" />
    <!--      搜索结果-->
    <div class="m-t-10 flex flex-items-center">
      <div class="m-r-4 text-20px">搜索结果</div>
      <el-button class="w-20" size="small" @click="tableVisible = !tableVisible"
        >{{ tableVisible ? '隐藏' : '显示' }}
      </el-button>
      <div class="m-l-20px text-16px"
        >{{ `${t('market.industryNews.keywords')}: ${keywords}` }}
      </div>
    </div>
    <el-table
      v-show="tableVisible"
      :data="metaTableData"
      border
      class="m-t-10px"
      v-loading="tableLoading"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center', background: '#f8f8f9', color: '#333333' }"
    >
      <el-table-column width="55" :label="t('market.industryNews.serialNumber')" type="index" />
      <el-table-column prop="title_cn" :label="t('market.industryNews.titleCn')" />
      <el-table-column prop="content_cn" :label="t('market.industryNews.AIPage')" />
      <el-table-column
        prop="link"
        :label="t('market.industryNews.link')"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          <ElLink type="primary" :href="row.url" target="_blank"> 跳转</ElLink>
          <ElButton
            link
            class="m-l-4"
            type="primary"
            @click="(copy(row.url) as any) && ElMessage.success('复制成功')"
          >
            复制
          </ElButton>
        </template>
      </el-table-column>
    </el-table>
    <!--    生成-->
    <el-form :model="form" ref="formRef" :rules="rules as FormRules" inline class="m-t-60px">
      <el-form-item :label="t('market.industryNews.platform')" prop="channel_id">
        <el-select
          v-model="form.channel_id"
          :placeholder="t('market.industryNews.platformMsg')"
          style="width: 250px"
        >
          <el-option
            v-for="item in platformList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('market.industryNews.language')" prop="language_id">
        <el-select
          v-model="form.language_id"
          :placeholder="t('market.industryNews.languageMsg')"
          style="width: 250px"
        >
          <el-option
            v-for="item in languageList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('market.industryNews.group')" prop="account_group_id">
        <el-select
          v-model="form.account_group_id"
          :placeholder="t('market.industryNews.groupMsg')"
          style="width: 250px"
        >
          <el-option
            v-for="item in groupList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('market.industryNews.associatedMiners')">
        <el-cascader
          v-model="form.mining_machine"
          :options="associatedMinersOptions"
          :placeholder="t('market.industryNews.associatedMinersMsg')"
          :props="props"
          clearable
          style="width: 350px"
        />
      </el-form-item>
      <el-form-item :label="t('market.industryNews.promptWords')">
        <el-popover placement="bottom" :width="400" :hide-after="0" trigger="click">
          <template #reference>
            <el-input
              v-model="form.cue_word"
              :placeholder="t('market.industryNews.promptWordsMsg')"
              readonly
              style="width: 350px"
            />
          </template>
          <el-input
            v-model="form.cue_word"
            type="textarea"
            :autosize="{ minRows: 15, maxRows: 20 }"
            :placeholder="t('market.industryNews.promptWordsMsg')"
          />
        </el-popover>
      </el-form-item>
      <el-form-item>
        <div class="flex flex-items-center">
          <UploadFile
            url="/common/uploadFile"
            ref="UploadFileRef"
            upload-file-button-name="上传图片"
            :file-type="['png', 'jpg', 'jpeg', 'bmp']"
            :params="{ directory: 2 }"
            list-type="text"
            :show-file-list="true"
            @upload-success-res="handleUploadCallback"
            @handle-remove-file="handleRemoveFile"
            @handle-picture-card-preview="handlePictureCardPreview"
          />
          <el-button type="primary" class="m-l-20px" @click="submit(formRef)">生成</el-button>
        </div>
      </el-form-item>
    </el-form>
    <el-table
      :data="produceTableData"
      border
      class="m-t-10px"
      v-loading="tableLoading"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center', background: '#f8f8f9', color: '#333333' }"
    >
      <el-table-column :label="t('expandCustomer.serialNumber')" prop="id" min-width="70" />
      <el-table-column
        :label="t('market.markSocialMediaAccount.channel')"
        min-width="200"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(platformList, row.channel_id) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('market.markSocialMediaAccount.language')"
        min-width="200"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(languageList, row.language_id) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('market.industryNews.group')"
        min-width="200"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(groupList, row.account_group_id) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('market.industryNews.miners')"
        prop="mining_machine"
        min-width="250"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{
            row.mining_machine
              ? `${JSON.parse(row.mining_machine).brand} ${JSON.parse(row.mining_machine).name}`
              : ''
          }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('market.industryNews.newsHeadlines')"
        prop="crypto_news_title"
        min-width="350"
      />
      <el-table-column
        :label="t('market.industryNews.promptWords')"
        prop="cue_word"
        min-width="400"
      />
      <el-table-column :label="t('market.industryNews.img')" min-width="200">
        <template #default="{ row }">
          <el-image
            v-if="row.imgs && row.imgs.length"
            :src="row.imgs[0].url"
            class="w-90px h-90px cursor-pointer"
            :zoom-rate="1.2"
            :max-scale="7"
            :preview-teleported="true"
            :min-scale="0.2"
            :preview-src-list="dealPreviewMap(row.imgs)"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column
        :label="t('market.industryNews.creationTime')"
        prop="create_time"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="{ row }">
          <el-button
            type="success"
            @click="handleJump('SMCopywritingTasksDetail', row)"
            size="small"
          >
            {{ t('market.markSocialMediaAccount.detail') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentDetailWrap>
</template>

<script setup lang="ts">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { Descriptions } from '@/components/Descriptions'
import { BaseButton } from '@/components/Button'
import { ElButton, ElMessage, type FormInstance, type FormRules } from 'element-plus'
import UploadFile from '@/components/UploadFile/index.vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useClipboard } from '@vueuse/core'
import { useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { getInfoApi, getPlatformSelectApi, publishConfigApi } from '@/api/market'
import useSchema from './components/hooks/useSchema'
import { createImageViewer } from '@/components/ImageViewer'

const { t } = useI18n()
const { push, go } = useRouter()
const { query } = useRoute()
const { copy } = useClipboard()

const currentRow = ref<Record<string, any>>({})

const tableVisible = ref(true)
const tableLoading = ref(false)
const metaTableData = ref<any[]>([])
const produceTableData = ref<any[]>([])

const props = reactive({
  value: 'value',
  label: 'label',
  children: 'children'
})

const platformList = ref<any[]>([])
const languageList = ref<any[]>([])
const groupList = ref<any[]>([])
const associatedMinersOptions = ref<any[]>([])
const UploadFileRef = ref()
const keywords = computed(() => (metaTableData.value.length ? metaTableData.value[0].keyword : ''))

const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  channel_id: '',
  language_id: '',
  account_group_id: '',
  mining_machine: [],
  cue_word: '',
  imgs: []
})
const rules = ref<FormRules>({
  channel_id: [
    {
      required: true,
      message: t('market.industryNews.platformMsg'),
      trigger: 'change'
    }
  ],
  language_id: [
    {
      required: true,
      message: t('market.industryNews.languageMsg'),
      trigger: 'change'
    }
  ],
  account_group_id: [
    {
      required: true,
      message: t('market.industryNews.groupMsg'),
      trigger: 'change'
    }
  ]
})

const dealPreviewMap = (val: any[]) => {
  if (!val || !val.length) return []
  return val.map((item) => item.url)
}
const handleRemoveFile = (val: any) => {
  if (form.value.imgs && form.value.imgs.length) {
    form.value.imgs = form.value.imgs.filter(
      (item: Record<string, any>) => item.uploadFile.uid !== val.uid
    )
  }
}
//上传成功以后回调
const handleUploadCallback = (val: any) => {
  form.value.imgs.push(val)
}
const handlePictureCardPreview = (val: any) => {
  if (!val) return
  createImageViewer({
    urlList: [val]
  })
}
//生成
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      const params = JSON.parse(JSON.stringify(form.value))
      params.mining_machine = params.mining_machine ? params.mining_machine[1] : null
      params.imgs = params.imgs.map((item: Record<string, any>) => item.id)
      const resp = await publishConfigApi({
        ...params,
        crypto_news_id: parseInt(query.id as string)
      })
      if (resp.code === 0) {
        ElMessage.success(t('market.industryNews.generateMsg'))
        reset(formEl)
        await nextTick(() => {
          UploadFileRef.value.fileList = []
        })
        await getInventoryInfo()
      }
    }
  })
}
//重置表单
const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.value = {
    channel_id: '',
    language_id: '',
    account_group_id: '',
    mining_machine: [],
    cue_word: '',
    imgs: []
  }
  formEl.resetFields()
}
//获取枚举
const getEnumerateList = async () => {
  const resp = await getPlatformSelectApi({ field: 'all' })
  platformList.value = resp.data.channel
  languageList.value = resp.data.language
  groupList.value = resp.data.account_group
  associatedMinersOptions.value = resp.data.mining_machine
}
//点击跳转
const handleJump = (type: string, row?: Record<string, any>) => {
  push({
    path: `/market/industryNews/${type}`,
    query: { [(row && 'id') as string]: row?.id }
  })
}
// 获取详情数据
const getInventoryInfo = async () => {
  try {
    tableLoading.value = true
    const res = (await getInfoApi(query.id as string)) as any
    currentRow.value = res.data
    metaTableData.value = res.data.news_search_det
    produceTableData.value = res.data.copywriting_tasks
    tableLoading.value = false
  } catch (e) {
    tableLoading.value = false
  }
}
//根据接口枚举匹配出中文名称
const useEnumeratePicker = (
  enumList: any[],
  field: string | number,
  key?: string,
  value?: string
) => {
  if (!enumList) return
  const matchItem =
    enumList.find((item: Record<string, any>) => item[value ?? 'value'] === field) || {}
  return matchItem[key ?? 'label'] || ''
}

getInventoryInfo()
getEnumerateList()
const { crudSchemas } = useSchema()
const { allSchemas } = useCrudSchemas(crudSchemas)
</script>

<style lang="less" scoped>
@import url('@/styles/global.less');

:deep(.el-upload-list) {
  display: inline-block;
  margin: 0;
}

:deep(.el-upload-list__item .el-upload-list__item-info) {
  width: 150px;
}
</style>
